package com.pine.common.captcha.config;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import com.pine.common.captcha.core.CaptchaFontStyleEnum;
import com.pine.common.captcha.core.CaptchaGeneratorTypeEnum;
import jakarta.annotation.Resource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.awt.*;

/**
 * 验证码配置
 *
 * @author pine manage
 * @since 2024-08-21
 */
@Configuration
@EnableConfigurationProperties({CaptchaProperties.class, CaptchaCodeProperties.class, CaptchaFontProperties.class})
public class CaptchaConfig {
    @Resource
    private CaptchaCodeProperties captchaCodeProperties;
    @Resource
    private CaptchaFontProperties captchaFontProperties;

    /**
     * 验证码文字生成器
     */
    @Bean
    public CodeGenerator codeGenerator() {
        CaptchaGeneratorTypeEnum generatorType = captchaCodeProperties.getCaptchaGeneratorType();
        int codeLength = captchaCodeProperties.getLength();
        return switch (generatorType) {
            case MATH -> new MathGenerator(codeLength);
            case RANDOM -> new RandomGenerator(codeLength);
        };
    }

    /**
     * 验证码字体
     */
    @Bean
    @SuppressWarnings("all")
    public Font captchaFont() {
        String fontName = captchaFontProperties.getName();
        int fontSize = captchaFontProperties.getSize();
        CaptchaFontStyleEnum style = captchaFontProperties.getStyle();
        return new Font(fontName, style.getStyle(), fontSize);
    }
}
